using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using memdb_demo.Interop.WrapModels;
using memdb_demo.Utils.Exceptions;

namespace memdb_demo.Interop{
    public partial class BizInterfaceWrapper{

        protected OrderQueryWrapper orderQueryWrapper =null;

        public BizInterfaceWrapper(){
            orderQueryWrapper  = new OrderQueryWrapper();
        }
        public BizInterfaceWrapper(OrderQueryWrapper wrapper){
            orderQueryWrapper  = wrapper;
        }

        public virtual Response<Record<Order>> QueryOrder(QueryRequest request){
            try{

                //1.create option
                //2.set option
                var optionHandle = orderQueryWrapper.CreateOrderQueryOption(request.Offset,request.Size);
                //3.create data
                var dataHandle = orderQueryWrapper.CreateOrderQueryData(request.Size);
                //4.call query
                var rtn = orderQueryWrapper.ExcuteOrderQuery(optionHandle,dataHandle);
                //5.get currentcount
                var realCount = orderQueryWrapper.GetOrderQueryDataCurrentCount(dataHandle);
                //6.get datacollection
                var resultHandle = orderQueryWrapper.GetOrderQueryDataCollection(dataHandle);
                //7.convert 
                var orderList = orderQueryWrapper.Deserialize(resultHandle,(int)realCount);//cannot marshal long size!!!!!!
                //8.destroy data
                orderQueryWrapper.DestroyOption(optionHandle);
                //9.destroy option
                orderQueryWrapper.DestroyData(dataHandle);
                return new Response<Record<Order>>{
                    IsSuccess = true,
                    Data = orderList
                };

            } catch(InterfaceWrapperException ex){
                return new Response<Record<Order>>{
                    IsSuccess=false,
                    ErrorMessage = ex.Message
                };
            }
            // //MOCK 
            // return new Response<Record<Order>>{
            //     IsSuccess = true,
            //     Data = new List<Record<Order>>{
            //         new Record<Order>{
            //             Key = new StringBuilder("testkey1"),
            //             Value = new Order{
            //                 OrderNo = Encoding.Default.GetBytes("testOrderNo1"),
            //                 BuySellFlag = (byte)'b',
            //             }
            //         }
            //     }
            // };

        }

    }

}

